<template>
  <el-card class="style-information-component">
    <el-form-item label="商品图片" />
    <div class="upload-wrap">
      <DraggableImageUpload v-model="form.imgs" :limit="10" />
    </div>
    <el-form-item label="款式设置">
      <el-radio-group v-model="form.attrStyle" @change="attrStyleChange">
        <el-radio :label="0">单款式</el-radio>
        <el-radio :label="1">多款式</el-radio>
      </el-radio-group>
    </el-form-item>
    <div class="style-container">
      <div v-if="form.attrStyle === 0" class="single-style">
        <el-table
          :data="skuList"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        >
          <el-table-column label="规格">
            <template #default="scope">
              <el-input
                v-model="singleStyle.skuValue"
                :sss="scope"
              />
            </template>
          </el-table-column>
          <el-table-column label="售价">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.price"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </template>
          </el-table-column>
          <el-table-column label="原价">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.originalPrice"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.stockNumber"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="重量(KG)">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.weight"
                :controls="false"
                :max="999"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </template>
          </el-table-column>
          <el-table-column label="条形码">
            <template #default="scope">
              <el-input v-model="scope.row.sku" maxlength="20" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="multiple-styles">
        <div
          v-for="(skuAttr, index) in form.skuAttrList"
          :key="index"
          class="sku-attr-list"
        >
          <el-form-item label="规格名">
            <el-input
              v-model="skuAttr.skuName"
              @change="val => noRepeatSku(val, index)"
            >
              <template #suffix>
                <el-icon v-if="index !== 0" class="el-input__icon delImg" @click="delSkuAttrList(index)"><Close /></el-icon>
              </template>
            </el-input>
            <!-- <el-icon v-if="index !== 0" class="delImg" @click="delSkuAttrList(index)"><Close /></el-icon> -->
            <el-checkbox
              v-if="index === 0"
              v-model="skuAttr.needImg"
              style="margin-left: 20px"
            >需要配图</el-checkbox>
          </el-form-item>
          <el-form-item label="规格值">
            <div class="attr-value-list">
              <div
                v-for="(sku, index1) in skuAttr.values"
                :key="index + '-' + index1"
                class="main-diagram m-8"
              >
                <el-input v-model="sku.skuValue">
                  <template #suffix>
                    <i v-if="index === 0 && index1 === 0"></i>
                    <el-icon v-else class="el-input__icon delImg" @click="delValue(index,index1)"><Close /></el-icon>
                  </template>
                </el-input>
                <!-- <i v-if="index === 0 && index1 === 0"></i>
                <el-icon v-else class="delImg" @click="delValue(index,index1)"><Close /></el-icon> -->
                <div
                  v-if="skuAttr.needImg && index === 0"
                  class="upload-wrap diagram-upload"
                >
                  <SingleUpload v-model="sku.image" />
                </div>
              </div>
              <el-button
                type="primary"
                link
                style="margin-left: 10px"
                @click="addAttrValue(index)"
              >添加</el-button>
            </div>
          </el-form-item>
        </div>
        <el-button
          class="add-attr-btn"
          type="primary"
          @click="addSkuAttrList"
        >添加规格</el-button>
        <div class="diy-table">
          <div class="diy-table-header">
            <div
              v-for="(skuAttr, index) in skuAttrName"
              :key="index"
              class="diy-table-header-item"
            >
              {{ skuAttr.skuName }}
            </div>
            <div class="diy-table-header-item">售价</div>
            <div class="diy-table-header-item">原价</div>
            <div class="diy-table-header-item">库存</div>
            <div class="diy-table-header-item">重量(KG)</div>
            <div class="diy-table-header-item">条形码</div>
          </div>
          <div
            v-for="(sku, index) in skuList"
            :key="index"
            class="diy-table-row"
          >
            <div
              v-for="(skuAttr, index1) in skuAttrName"
              :key="index + '-' + index1"
              class="diy-table-row-item"
            >
              {{
                attrValueFilter(
                  sku.skuAttrCodeDTOList && sku.skuAttrCodeDTOList[index1],
                  form.skuAttrList
                )
              }}
            </div>
            <div class="diy-table-row-item">
              <el-input-number
                v-model="sku.price"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </div>
            <div class="diy-table-row-item">
              <el-input-number
                v-model="sku.originalPrice"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </div>
            <div class="diy-table-row-item">
              <el-input-number
                v-model="sku.stockNumber"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="0"
              />
            </div>
            <div class="diy-table-row-item">
              <el-input-number
                v-model="sku.weight"
                :controls="false"
                :max="999"
                :min="0"
                :precision="6"
                :step="0.01"
              />
            </div>
            <div class="diy-table-row-item">
              <el-input v-model="sku.sku" maxlength="20" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="visible.image"
      :append-to-body="true"
      class="check-image-dialog"
      title="查看图片"
      center="center"
    >
      <img width="100%" :src="detailImage" alt />
    </el-dialog>
  </el-card>
</template>

<script setup>
import { computed, defineComponent, reactive, ref, shallowRef, toRefs, watch } from 'vue';
import { ElMessage } from 'element-plus';
import DraggableImageUpload from '@/components/Upload/DraggableImageUpload/index.vue'
import SingleUpload from '@/components/Upload/SingleUpload/index.vue'

defineComponent({
  name: 'CommodityFormInfo'
})

const props = defineProps({
  form: {
    type: Object,
    default () {
      return {}
    },
  },
})

let { form } = toRefs(props);

let uploadSetting = reactive({
  data: {
    folderId: 1,
  }
})

function attrValueFilter (map, list) {
  const hasChilds =
        list &&
        list.filter((skuAttr) => {
          const hasChild = skuAttr.values.some((attr) => {
            return attr.skuValue
          })
          return skuAttr.skuName && hasChild
        })
  if (!map) {
    return ''
  }
  const { code, valueCode } = map
  let codeStr = ''
  hasChilds.map((item) => {
    const { values } = item
    values &&
          values.some((attr) => {
            const isSome = item.code === code && attr.valueCode === valueCode
            if (isSome) {
              codeStr = attr.skuValue
            }
            return isSome
          })
  })
  return codeStr
}
function noRepeatSku (val, index) {
  let isRepeat = false
  form.value.skuAttrList.forEach((sku, skuIndex) => {
    if (sku.skuName === val && skuIndex !== index) {
      isRepeat = true
    }
  })
  if (isRepeat) {
    ElMessage.warning('已存在相同规格')
    form.value.skuAttrList[index].skuName = ''
  }
  // return isRepeat ? '' : val
}

let skuAttrName = computed(() => {
  return (
    form.value.skuAttrList &&
        form.value.skuAttrList.filter((skuAttr) => {
          const hasChilds = skuAttr.values.some((attr) => {
            return attr.skuValue
          })
          return skuAttr.skuName && hasChilds
        })
  )
})

let singleStyle = computed(() => {
  if (form.value.skuAttrList && form.value.skuAttrList[0]) {
    return form.value.skuAttrList && form.value.skuAttrList[0].values[0]
  }
  return {
    skuValue: '',
  }
})

let skuList = computed(() => {
  if (form.value.attrStyle === 0) {
    return form.value.skuList.slice(0, 1)
  }
  return form.value.skuList
})

let visible = reactive({
  image: false,
})

let detailImage = shallowRef('');

function addSkuAttrList () {
  form.value.skuAttrList.push({
    code: '',
    skuName: '',
    values: [
      {
        skuValue: '',
        valueCode: '',
        image: '',
        isDelete: 0,
        sortOrder: 0,
      },
    ],
    isDelete: 0,
    needImg: 0,
    sortOrder: 0,
  })
}
function addAttrValue (index) {
  form.value.skuAttrList[index].values.push({
    skuValue: '',
    valueCode: '',
    image: '',
  })
}
// 删除规格值
function delValue (index, index1) {
  const newList = JSON.parse(JSON.stringify(form.value.skuAttrList[index]))
  const valueObj = {
    code: newList.code,
    skuId: newList.skuId,
    valueCode: newList.values[index1].valueCode
  }
  form.value.deletes.push(valueObj)
  form.value.skuAttrList[index].values.splice(index1, 1)
}
// 删除规格名
function delSkuAttrList (index) {
  const newList = JSON.parse(JSON.stringify(form.value.skuAttrList[index]))
  newList.values.forEach(item => {
    const valueObj = {
      code: newList.code,
      skuId: newList.skuId,
      valueCode: ''
    }
    valueObj.valueCode = item.valueCode
    form.value.deletes.push(valueObj)
  })
  form.value.skuAttrList.splice(index, 1)
}

function skuFormat () {
  // 初始化新的 SKU 列表
  const skuListArray = [];

  // 生成现有 SKU 的映射，以便之后保留其价格、库存等数据
  const existingSkuMap = new Map();
  form.value.skuList.forEach(item => {
    const key = JSON.stringify(item.skuAttrCodeDTOList); // 确保这里生成的键唯一且准确
    existingSkuMap.set(key, {
      price: item.price,
      originalPrice: item.originalPrice,
      stockNumber: item.stockNumber,
      weight: item.weight,
      sku: item.sku,
      skuImg: item.skuImg
    });
  });

  const values = form.value.skuAttrList.map((skuItem, index) => {
    const attrList = [];
    skuItem.code = skuItem.code || `attr_code_${index}`;
    skuItem.values.forEach((attrItem, index1) => {
      attrItem.valueCode = attrItem.valueCode || `${skuItem.code}_value_${index1}`;
      if (attrItem.skuValue) {
        attrList.push({
          skuId: attrItem.skuId,
          attrId: attrItem.attrId,
          code: skuItem.code,
          valueCode: attrItem.valueCode
        });
      }
    });
    return attrList;
  }).filter(attrList => attrList.length > 0);
  if (values.length) {
    const doExchange = (arr, depth, currentResult) => {
      for (let i = 0; i < arr[depth].length; i++) {
        const { code, valueCode, attrId } = arr[depth][i];
        currentResult.skuAttrCodeDTOList[depth] = { code, valueCode, attrId };

        if (depth !== arr.length - 1) {
          doExchange(arr, depth + 1, currentResult);
        } else {
          console.log(form.value.skuList, 'skuList-1--')
          const newSkuItem = {
            isDelete: 0,
            productId: '',
            skuAttrCodeDTOList: JSON.parse(JSON.stringify(currentResult.skuAttrCodeDTOList)),
            sku: '',
            skuImg: '',
            price: 0,
            originalPrice: 0,
            stockNumber: 0,
            weight: 0,
          };

          const key = JSON.stringify(newSkuItem.skuAttrCodeDTOList);

          if (existingSkuMap.has(key)) {
            console.log('增加suk-------')
            const existingData = existingSkuMap.get(key);
            newSkuItem.price = existingData.price;
            newSkuItem.originalPrice = existingData.originalPrice;
            newSkuItem.stockNumber = existingData.stockNumber;
            newSkuItem.weight = existingData.weight;
            newSkuItem.sku = existingData.sku;
            newSkuItem.skuImg = existingData.skuImg;
          }
          skuListArray.push(newSkuItem);

          console.log(form.value.skuList, 'skuList-2-', skuListArray, 'skuListArray')
        }
      }
    };

    doExchange(values, 0, { skuAttrCodeDTOList: [] });
  }
  // 更新 form 的 SKU 列表
  form.value.skuList = skuListArray;
}

// 款式设置改变
function attrStyleChange () {
  setSkuAttr()
}

function setSkuAttr () {
  if (form.value.attrStyle === 1) {
    // 判断是否有规格值
    const hasChilds =
        form.value.skuAttrList &&
        form.value.skuAttrList.filter((skuAttr) => {
          const hasChild = skuAttr.values.some((attr) => {
            return attr.skuValue
          })
          return skuAttr.skuName && hasChild
        })
    if (hasChilds.length) {
      skuFormat()
    }
  }
}

watch(() => form.value.skuAttrList, (_newVal, _oldVal) => {
  console.log(_newVal)
  setSkuAttr()
}, { deep: true })
</script>

<style lang="scss" scoped>
.style-information-component {
  width: 100%;
  min-height: 300px;
  // padding: 24px;
  // background-color: rgb(255, 255, 255);
  .el-form-item {
    margin-bottom: 10px;
  }
  .attr-value-list {
    display: flex;
    flex-wrap: wrap;
    .main-diagram {
      width: 180px;
      .span-wrap {
        position: relative;
        display: inline-block;
        margin-top: 10px;
        .attr-actions {
          line-height: 100px;
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          cursor: default;
          text-align: center;
          color: #fff;
          opacity: 0;
          font-size: 20px;
          background-color: rgba(0, 0, 0, 0.5);
          -webkit-transition: opacity 0.3s;
          transition: opacity 0.3s;
          z-index: 1;
          &:hover {
            opacity: 1;
            .attr-preview {
              display: inline-block;
            }
            i {
              color: #fff;
              font-size: 20px;
            }
          }
        }
        .attr-preview {
          display: none;
          cursor: pointer;
          font-size: 20px;
          color: #fff;
        }
        .attr-delete {
          margin-left: 15px;
          color: #fff;
        }
      }
      .attr-value-img {
        width: 100%;
        height: 100%;
        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
  }
  .m-8 {
    margin-right: 8px;
  }
  .upload-btn {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 110px;
    cursor: pointer;
    border: 2px dashed #2e60f8;
    border-radius: 2px;
    background-color: #f8f9fb;
    text-align: center;
    font-size: 20px;
    color: #2e60f8;
    i {
      color: #2e60f8;
      font-size: 20px;
    }
    .upload-title {
      margin-left: 10px;
      font-size: 14px;
    }
  }
  .diagram-upload{
    margin-top: 10px;
  }
  .upload-wrap {
    margin-bottom: 25px;
    .el-upload-list__item {
      transition: none !important;
    }
    .el-upload,
    .el-upload-list__item {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }
    .el-progress,
    .el-progress-circle {
      width: 80px !important;
      height: 80px !important;
    }
  }
  .sku-attr-list {
    .el-input {
      width: 180px;
    }
  }
  .single-style {
    .el-input {
      max-width: 180px;
    }
  }
  .add-attr-btn {
    margin-bottom: 25px;
  }
  .check-image-dialog {
    .el-dialog {
      margin-top: 25px;
      .el-dialog__body {
        img {
          max-width: 100%;
          max-height: 100%;
          height: 500px;
          object-fit: contain;
        }
      }
    }
  }
  // .delImg {
  //   position: absolute;
  //   top: 12px;
  //   margin-left: -24px;
  // }
  .delImg:hover {
    // border-radius: 50%;
    color: #ffffff;
    background: #2e60f8;
    cursor: pointer;
  }
}

.diy-table{
  .diy-table-header{
    display: flex;
    padding: 12px 0;
    background-color: #eef3ff;
    color: #333;
    font-weight: bold;
    .diy-table-header-item{
      flex: 1;
      padding: 0 5px;
    }
  }
  .diy-table-row{
    display: flex;
    padding: 8px 0;
    border-bottom: 1px solid #ebeef5;
    align-items: center;
    .diy-table-row-item{
      flex: 1;
      padding: 0 5px;
      .el-input,.el-input-number{
        width: 100%;
      }
    }
  }
}
</style>
